import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'

import { Button, Popover, message, Col, Row, Form, Select, DatePicker,Radio, Input} from 'antd';
const Option = Select.Option;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const MonthPicker = DatePicker.MonthPicker;

import waitForBillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service'
import DepartmentPicker from 'containers/financial-management/wait-for-billing/new-billing/department-picker'
import Chooser from 'components/chooser'
import moment from 'moment'

class NewBillingForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sectionMatch: {
        companyName: "-"
      },
      radioValue:'all',
      companyAccountOptions: [],
      paymentTypeOptions: [{label:messages('financial-management.key432'/*全部*/),key:null},{label:messages('financial-management.key411'/*个人垫付*/) , key: '1001'}, {label: messages('financial-management.key412'/*公司垫付*/), key: '1002'}],
      commercialTypeOptions: [{label:messages('financial-management.key454'/*不含商务卡*/),key:'NOT_INCLUDE'},{label:messages('financial-management.key432'/*全部*/),key:'ALL'}],
      baseDateOptions: [{label: messages('financial-management.key564')/*审核日期*/,key:'AUDIT_PASS_DATE'}],
      isHaveCommercial: false,
      billingType: props.billingType,
    };
  }

  componentDidMount(){
    const { billingType } = this.state;
    let paymentTypeOptions = this.state.paymentTypeOptions;
    // if(billingType === 'DIDI'){
    //   paymentTypeOptions = [{label:messages('financial-management.key411'/*个人垫付*/) , key: '1001'}];
    // }
    this.setState({paymentTypeOptions});
    if (this.state.billingType != 'CLOUD_HELIOS_HOTEL') {
      waitForBillingService.getCompanyAccount(this.state.billingType,this.props.company.companyOID).then(res => {
        this.setState({companyAccountOptions: res.data})
      });
    }
    let commercialTypeOption = this.state.commercialTypeOptions;
    let weatherCommercial = this.state.isHaveCommercial;
    waitForBillingService.getCommercialType(this.props.company.companyOID).then(res => {
      if(res.data.rows && res.data.rows.length>0){
        weatherCommercial = true;
        res.data.rows.map(item => {
          let values = {};
          values.label = item.description;
          values.key = item.cardTypeCode;
          commercialTypeOption.push(values);
        })
      }
      this.setState({ commercialTypeOptions : commercialTypeOption,isHaveCommercial : weatherCommercial });
    });
    this.props.form.setFieldsValue({dateRadio:'thisMonth'})
  }

  disabledDate = (startValue) => {
    return startValue && startValue.valueOf() > Date.now();
  }

  onEndChange = (value) => {
    const {getFieldValue,setFieldsValue}  = this.props.form;

    setFieldsValue({dateRadio:null})
    let promise = new Promise(function(resolve, reject) {
      if (getFieldValue('startDate') && value.isBefore(getFieldValue('startDate')))
        resolve('clear');
      else
        resolve('normal')
    });
    promise.then((result) => {
      if (result === 'clear') {
        message.error(messages('financial-management.key459'/*结束时间小于开始时间*/))
        setFieldsValue({endDate: null})
      }
    })
  }

  onStartChange = (value) =>{
    const {getFieldValue,setFieldsValue}  = this.props.form;

    setFieldsValue({dateRadio:null})
    let promise = new Promise(function(resolve, reject) {
      if (getFieldValue('endDate') && getFieldValue('endDate').isBefore(value))
        resolve('clear');
      else
        resolve('normal')
    });
    promise.then((result) => {
      if (result === 'clear') {
        message.error(messages('financial-management.key459'/*结束时间小于开始时间*/))
        setFieldsValue({startDate: null})
      }
    })
  }

  handleRadioChange = (e)=>{
    const {setFieldsValue}  = this.props.form;
    let date = new Date(), y = date.getFullYear(), m = date.getMonth();
    let firstDay = new Date(y, m, 1);
    let lastDay = new Date(y, m + 1, 0);
    if(e.target.value === 'thisMonth'){
        setFieldsValue({startDate:moment(moment(firstDay).format('YYYY-MM-DD'))})
    }else{
      setFieldsValue({startDate:null})
    }
  }

  saveReceiptConditions = (e)=>{
    e.preventDefault();
    const {companyAccountOptions,paymentTypeOptions,commercialTypeOptions,isHaveCommercial} = this.state;

    if(this.state.billingType !== 'CLOUD_HELIOS_HOTEL' && companyAccountOptions.length ===0){
      message.error(messages('financial-management.key480'/*该供应商未在中间件开户*/));
      return
    }
    this.props.form.validateFieldsAndScroll((err,values) => {
      let paymentTypeTemp = {};
      let commercialTypeTemp = {};
      let companyTemp = {};
      if (this.state.billingType !== 'CLOUD_HELIOS_HOTEL') {
        companyTemp.vendorAccountId = values.vendorAccountId;
        companyTemp.vendorAccountName = companyAccountOptions.filter(item => item.vendorAccountId === values.vendorAccountId)[0].vendorAccountName;
        values.company = companyTemp;
      }
      
      values.isHaveCommercial = isHaveCommercial;
      this.props.newBillingRule(values)
     })
    }

  //查询开票
  searchTicket = (e)=>{
    e.preventDefault();
    const {companyAccountOptions,paymentTypeOptions,commercialTypeOptions,isHaveCommercial } = this.state;
    if(this.state.billingType !== 'CLOUD_HELIOS_HOTEL' && companyAccountOptions.length === 0){
      message.error(messages('financial-management.key480'/*该供应商未在中间件开户*/));
      return
    }
    this.props.form.validateFieldsAndScroll((err,values) => {
      let paymentTypeTemp = {};
      let commercialTypeTemp = {};
      if(this.state.billingType !== 'CLOUD_HELIOS_HOTEL' ){
        let companyTemp = {};
        companyTemp.vendorAccountId = values.vendorAccountId;
        companyTemp.vendorAccountName =  companyAccountOptions.filter(item => item.vendorAccountId === values.vendorAccountId)[0].vendorAccountName;
        values.company = companyTemp;
      }
      
      this.props.toSearchBilling(values)
    })
  };

  handleClear = ()=>{
    this.props.form.resetFields();
    this.props.form.setFieldsValue({startDate:''});
  };

  renderBillingType = () => {
    const { billingType } = this.state;
    let result = '';
    switch (billingType){
      case 'DIDI':
        result = messages('financial-management.key423'/*滴滴账户*/);
        break;
      case 'CLOUD_HELIOS_HOTEL':
        result = messages('financial-management.key548'/*甄选账号*/);
        break;
      case 'SHEN_ZHOU':
        result = messages('financial-management.key549'/*神州账户*/);
        break;
      default:
        result = '';
        break;
    }
    return result;
  };

  render(){
    const { companyAccountOptions, paymentTypeOptions, commercialTypeOptions, isHaveCommercial,baseDateOptions,radioValue, billingType } = this.state;
    const { getFieldDecorator } = this.props.form;
    let date = new Date(), y = date.getFullYear(), m = date.getMonth();
    let firstDay = new Date(y, m, 1);
    let lastDay = new Date(y, m + 1, 0);
    return (
      <div style={{ width: '100%' }}>
        <Form>
          <Row gutter={30} type="flex" align="top">
            <Col span={8}>
              <FormItem label={messages('financial-management.key481'/*基准日期*/)}>
                {getFieldDecorator('recDateTypeEnum',{
                  initialValue: 'AUDIT_PASS_DATE'
                })(
                  <Select
                  defaultValue='AUDIT_PASS_DATE'>
                    {baseDateOptions.map(option => <Option key={option.key}>{option.label}</Option>)}
                  </Select>
                )}
              </FormItem>
            </Col>
            {false && <Col span={8}>
              <FormItem label={messages('financial-management.key482'/*时间范围*/)}>
                {getFieldDecorator('dateRadio',{
                  initialValue:"thisMonth"
                })(
                    <RadioGroup onChange={this.handleRadioChange} >
                      <Radio value="thisMonth">{messages('financial-management.key464'/*当月*/)}</Radio>
                      <Radio value="all">{messages('financial-management.key432'/*全部*/)}</Radio>
                    </RadioGroup>
                )}
              </FormItem>
            </Col>}
            <Col span={8}>
                  <FormItem label='请选择开票月份'>
                    {getFieldDecorator("startDate",{
                      // initialValue:moment(moment(firstDay).format('YYYY-MM'))
                    })(
                      <MonthPicker disabledDate={this.disabledDate}/>
                    )}
                  </FormItem>
            </Col>
            {billingType!=='CLOUD_HELIOS_HOTEL' && <Col span={8}>
              <FormItem label={this.renderBillingType()}>
                {getFieldDecorator('vendorAccountId',{
                  rules:[{
                    required:true
                  }],
                  initialValue:companyAccountOptions.length>0 ? companyAccountOptions[0].vendorAccountId : ''
                })(
                  <Select >
                    {companyAccountOptions.length && companyAccountOptions.map(option => <Option key={option.vendorAccountId}>{option.vendorAccountName}</Option>)}
                  </Select>
                )}
              </FormItem>
            </Col>}
            <Col span={8}>
              <FormItem label={messages('financial-management.key468'/*法人实体【单据信息】*/)}>
                {getFieldDecorator('expenseLegalEntity')(
                  <Chooser placeholder={messages('common.please.select')}
                           type='corporation_entity_all'
                           valueKey="companyName"
                           labelKey="companyName"
                           single={false}
                  />
                )}
              </FormItem>
            </Col>
           
           
          </Row>
          <div style={{height: "36px", clear: "both"}}>
            <Button type="primary" htmlType="submit" onClick={this.searchTicket}>{messages('financial-management.key485'/*查询开票*/)}</Button>
            <Button style={{ marginLeft: 8 }} htmlType="submit" onClick={this.saveReceiptConditions}>{messages('financial-management.key486'/*存为常用开票条件*/)}</Button>
            <Button style={{ marginLeft: 16 }} onClick={this.handleClear}>{messages('common.clear')}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

NewBillingForm.contextTypes = {
  router: React.PropTypes.object
};

NewBillingForm.propTypes = {
  newBillingRule:React.PropTypes.func,
  toSearchBilling:React.PropTypes.func
}
function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

const WrappedNewDidiBillingForm = Form.create()(NewBillingForm);

export default connect(mapStateToProps)(WrappedNewDidiBillingForm);
